﻿using Sidvall.UI.Dialogs;
using Sidvall.UI.ViewModels;
using System.Threading.Tasks;
using Windows.UI.Xaml.Controls;

namespace Sidvall.UI.Uwp.Controls
{
    public sealed partial class SecurityControl
    {
        #region Public Members

        public event System.EventHandler LogOnCompleted;
        public event System.EventHandler ViewTypeChanged;

        #region ViewModel

        public SecurityControlViewModel ViewModel
        {
            get
            {
                return (SecurityControlViewModel)this.DataContext;
            }
            set
            {
                this.DataContext = value;
            }
        }

        #endregion
        #region ViewType

        public SecurityControlViewType ViewType
        {
            get
            {
                return (SecurityControlViewType)this.TabControl.SelectedIndex;
            }
            set
            {
                this.TabControl.SelectedIndex = (int)value;
                this.ViewModel.ViewType = value;
                OnViewTypeChanged();
            }
        }

        #endregion

        #region DoPrimaryActionAsync

        public async Task DoPrimaryActionAsync()
        {
            switch (this.ViewType)
            {
                case SecurityControlViewType.LogOnView:
                    await LogOnAsync();
                    break;
                case SecurityControlViewType.SubmitCodeView:
                    await SendCodeAsync();
                    break;
                case SecurityControlViewType.ResetPasswordView:
                    await SendResetPasswordEmailAsync();
                    break;
                case SecurityControlViewType.NewPasswordEmailView:
                    this.ViewType = SecurityControlViewType.LogOnView;
                    break;
                default:
                    break;
            }
        }

        #endregion
        #region DoSecondaryActionAsync

        public Task DoSecondaryActionAsync()
        {
            switch (this.ViewType)
            {
                case SecurityControlViewType.LogOnView:
                    OnLogOnCompleted();
                    break;
                case SecurityControlViewType.SubmitCodeView:
                    OnLogOnCompleted();
                    break;
                case SecurityControlViewType.ResetPasswordView:
                    OnLogOnCompleted();
                    break;
                case SecurityControlViewType.NewPasswordEmailView:
                    OnLogOnCompleted();
                    break;
                default:
                    break;
            }
            return Task.FromResult(true);
        }

        #endregion
        #region InitializeContextAsync

        public async Task InitializeContextAsync(LogOnDialogContext logOnContext, LogOffDialogContext logOffContext, SecurityControlViewModelSettings viewModelSettings)
        {
            if ((logOnContext == null) && (logOffContext == null))
                throw new System.ArgumentNullException(nameof(logOnContext));

            var item = new SecurityControlViewModel();
            await item.InitializeContextAsync(logOnContext, logOffContext, viewModelSettings);
            this.ViewModel = item;
        }

        #endregion
        #region StartAsync

        public async Task StartAsync()
        {
            if (_IsStarted)
                return;
            _IsStarted = true;
            if (this.ViewModel == null)
                return;
            if (this.ViewModel.LogOffDialogContext != null)
            {
                this.ViewType = SecurityControlViewType.LogOffView;
                await this.ViewModel.LogOffAsync();
            }
            if (this.ViewModel.LogOnDialogContext != null)
            {
                this.ViewType = SecurityControlViewType.LogOnView;
            }
            else
            {
                OnLogOnCompleted();
            }
        }

        #endregion

        #endregion
        #region Private Members

        private bool _IsStarted = false;
        private bool _IsBusy = false;

        #region LogOnAsync

        private async Task LogOnAsync()
        {
            if (_IsBusy)
                return;
            _IsBusy = true;
            await this.ViewModel.LogOnAsync(this.PasswordBox.Password);
            if (this.ViewModel.RequireCode)
            {
                this.ViewType = SecurityControlViewType.SubmitCodeView;
            }
            else if (this.ViewModel.LogOnDialogContext.AuthorizeResponse != null)
            {
                OnLogOnCompleted();
            }
            _IsBusy = false;
        }

        #endregion
        #region SendCodeAsync

        private async Task SendCodeAsync()
        {
            if (_IsBusy)
                return;
            _IsBusy = true;
            await this.ViewModel.SendCodeAsync();
            if (this.ViewModel.LogOnDialogContext.AuthorizeResponse != null)
                OnLogOnCompleted();
            _IsBusy = false;
        }

        #endregion
        #region SendResetPasswordEmailAsync

        private async Task SendResetPasswordEmailAsync()
        {
            if (_IsBusy)
                return;
            _IsBusy = true;
            await this.ViewModel.SendResetPasswordEmailAsync();
            this.ViewType = SecurityControlViewType.NewPasswordEmailView;
            _IsBusy = false;
        }

        #endregion
        #region SetFocus

        private void SetFocus()
        {
            switch (this.ViewType)
            {
                case SecurityControlViewType.LogOffView:
                    break;
                case SecurityControlViewType.LogOnView:
                    if (string.IsNullOrWhiteSpace(this.ViewModel.UserName))
                        this.UserNameBox.Focus(Windows.UI.Xaml.FocusState.Programmatic);
                    else
                        this.PasswordBox.Focus(Windows.UI.Xaml.FocusState.Programmatic);
                    break;
                case SecurityControlViewType.SubmitCodeView:
                    this.CodeBox.Focus(Windows.UI.Xaml.FocusState.Programmatic);
                    break;
                case SecurityControlViewType.ResetPasswordView:
                    this.EmailBox.Focus(Windows.UI.Xaml.FocusState.Programmatic);
                    break;
                case SecurityControlViewType.NewPasswordEmailView:
                    break;
                default:
                    break;
            }
        }

        #endregion

        #region OnLogOnCompleted

        private void OnLogOnCompleted()
        {
            OnLogOnCompleted(new System.EventArgs());
        }
        private void OnLogOnCompleted(System.EventArgs args)
        {
            OnLogOnCompleted(this, args);
        }
        private void OnLogOnCompleted(object sender, System.EventArgs args)
        {
            if (this.LogOnCompleted != null)
                this.LogOnCompleted.Invoke(sender, args);
        }

        #endregion
        #region OnViewTypeChanged

        private void OnViewTypeChanged()
        {
            OnViewTypeChanged(new System.EventArgs());
        }
        private void OnViewTypeChanged(System.EventArgs args)
        {
            OnViewTypeChanged(this, args);
        }
        private void OnViewTypeChanged(object sender, System.EventArgs args)
        {
            if (this.ViewTypeChanged != null)
                this.ViewTypeChanged.Invoke(sender, args);
        }

        #endregion

        #endregion
        #region Events

        #region ChangePassword_Click

        private void ChangePassword_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            this.ViewType = SecurityControlViewType.ResetPasswordView;
        }

        #endregion
        #region GotoLogOn_Click

        private void GotoLogOn_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            this.ViewType = SecurityControlViewType.LogOnView;
        }

        #endregion
        #region LogOnControl_KeyDown

        private async void LogOnControl_KeyDown(object sender, Windows.UI.Xaml.Input.KeyRoutedEventArgs e)
        {
            if (e.Key == Windows.System.VirtualKey.Enter)
            {
                if ((this.ViewModel.CanLogOn) && (this.PasswordBox.Password.Length > 0))
                    await LogOnAsync();
                else
                    SetFocus();
            }
        }

        #endregion
        #region TabControl_PivotItemLoaded

        private void TabControl_PivotItemLoaded(Pivot sender, PivotItemEventArgs args)
        {
            SetFocus();
        }

        #endregion

        #endregion
        #region Constructors

        public SecurityControl()
        {
            this.InitializeComponent();

            this.TabControl.PivotItemLoaded += TabControl_PivotItemLoaded;
        }

        #endregion
    }
}
